<!-- 新增设备 -->
<template>
  <div class="base-info">
    <pageHeader
      v-if="type === 'add'"
      :title="title"
      :breadCrumb="breadCrumb"
      :show-back="true"
    >
    </pageHeader>
    <div>
      <div
        :style="{
          float: 'right',
          margin: '20px 20px',
        }"
      >
        <a-button type="outline" @click="edit" v-if="type !== 'add'">
          编辑
        </a-button>
      </div>
      <a-form
        auto-label-width
        ref="formRef"
        :model="form.list"
        :rules="rules"
        aut
        o-label-width
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="设备编码：" validate-trigger="blur" required>
              <a-input disabled placeholder="自动生成" size="large" />
              <a-tooltip
                content="设备编码:是做为公司内部固定资产识别编码，方面公司统一管理。根据公司固定资产编规则自动生成"
              >
                <icon-exclamation-circle-fill
                  size="20"
                  :style="{
                    color: '#165dff',
                  }"
                />
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="manufacturerNumber"
              label="设备厂商编号："
              required
            >
              <a-input
                placeholder="请输入设备厂商固有编号"
                size="large"
                v-model="form.list.manufacturerNumber"
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              field="deviceName"
              label="设备名称："
              validate-trigger="blur"
              required
            >
              <a-input
                placeholder="请输入设备名称"
                size="large"
                v-model="form.list.deviceName"
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="供应商："
              field="supplierID"
              validate-trigger="change"
              required
            >
              <a-select
                placeholder="请选择供应商"
                v-model="form.list.supplierID"
                :disabled="type !== 'add' && !isEdit"
                allow-search
                @change="(e) => selectSupplier(e as number)"
              >
                <a-option
                  v-for="item in supplierList.list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <div
                    :style="{
                      display: 'flex',
                      marginBottom: '10px',
                    }"
                  >
                    <div> {{ item?.name }}</div>
                    <!-- <div :class="item?.state === 1 ? 'success' : 'blacklist'"
                      >{{ item?.state === 1 ? '正常' : '黑名单' }}
                    </div> -->
                  </div>
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              field="specification"
              label="规格："
              validate-trigger="blur"
              required
            >
              <a-input
                placeholder="请输入设备规格"
                size="large"
                v-model="form.list.specification"
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="型号：">
              <a-input
                placeholder="请输入设备型号"
                size="large"
                v-model="form.list.modelNumber"
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              field="deviceTypeId"
              label="设备类型："
              validate-trigger="change"
              required
            >
              <a-tree-select
                :disabled="type !== 'add' && !isEdit"
                v-model="form.list.deviceTypeId"
                :fieldNames="{
                  key: 'id',
                  title: 'name',
                  children: 'children',
                }"
                :data="deviceType.data"
                placeholder="请选择设备类型"
              ></a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="deviceUse"
              label="设备用途："
              validate-trigger="blur"
              required
            >
              <a-input
                placeholder="请输入设备用途"
                size="large"
                v-model="form.list.deviceUse"
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              field="workshopId"
              label="所属车间："
              validate-trigger="blur"
              required
            >
              <a-select
                placeholder="请选择"
                v-model="form.list.workshopId"
                :disabled="type !== 'add' && !isEdit"
              >
                <a-option
                  v-for="item of workshop.data"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="存放位置：">
              <a-input
                placeholder="请输入存放位置"
                size="large"
                v-model="form.list.storageLocation"
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              field="responsiblePersonId"
              label="负责人："
              validate-trigger="change"
              required
            >
              <a-input
                placeholder="请选择人员"
                style="cursor: pointer"
                v-model="form.list.responsiblePersonName"
                :disabled="type !== 'add' && !isEdit"
                @click="personnelVisible = true"
              >
                <template #suffix>
                  <icon-down />
                </template>
              </a-input>
              <!-- <a-select
                placeholder="请选择人员"
                v-model="form.list.responsiblePersonName"
                :disabled="type !== 'add' && !isEdit"
                @click="personnelVisible = true"
              >
                <a-option>人员A</a-option>
                <a-option>人员B</a-option>
                <a-option>人员C</a-option>
                <a-option>人员D</a-option>
              </a-select> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="productionDate"
              label="投产日期："
              validate-trigger="blur"
              required
            >
              <!-- {{ form.list.productionDate }} -->
              <a-date-picker
                v-model="form.list.productionDate"
                style="width: 100%"
                show-time
                format="YYYY-MM-DD HH:mm"
                placeholder="请选择时间"
                value-format="x"
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              field="purchaseAmount"
              label="设备购置金额："
              validate-trigger="blur"
              required
            >
              <a-input-number
                :min="1"
                placeholder="请输入设备购置金额"
                size="large"
                v-model="form.list.purchaseAmount"
                :disabled="type !== 'add' && !isEdit"
                hide-button
              >
                <template #append>
                  <a-select
                    placeholder="币种"
                    v-model="form.list.purchaseAmountUnit"
                    :disabled="type !== 'add' && !isEdit"
                  >
                    <a-option :value="1">人民币</a-option>
                    <a-option :value="2">美元</a-option>
                  </a-select></template
                >
              </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="设备安装费用：">
              <a-input-number
                :min="1"
                placeholder="请输入设备安装费用"
                size="large"
                v-model="form.list.installationCost"
                :disabled="type !== 'add' && !isEdit"
                hide-button
              >
                <template #append>
                  <a-select
                    placeholder="币种"
                    v-model="form.list.installationCostUnit"
                    :disabled="type !== 'add' && !isEdit"
                  >
                    <a-option :key="1" :value="1">人民币</a-option>
                    <a-option :key="2" :value="2">美元</a-option>
                  </a-select></template
                >
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="设备品牌：">
              <a-input
                placeholder="请输入设备品牌"
                size="large"
                v-model="form.list.brand"
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="periodOfDepreciation"
              label="设备折旧年限："
              required
            >
              <a-input-number
                :min="1"
                placeholder="请输入设备折旧年限"
                size="large"
                v-model="form.list.periodOfDepreciation"
                :disabled="type !== 'add' && !isEdit"
                hide-button
              >
                <!-- <template #append>
                  <a-select
                    placeholder="单位"
                    v-model="form.list.equipmentLife.equipmentLifeUnit"
                    :disabled="type !== 'add' && !isEdit"
                  >
                    <a-option>年</a-option>
                    <a-option>月</a-option>
                    <a-option>日</a-option>
                  </a-select>
                </template> -->
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="设备年龄：">
              <a-input-number
                :min="1"
                placeholder="第一次可以直接输入设备真实年龄，往后以时间自动计算"
                size="large"
                v-model="form.list.equipmentAge"
                :disabled="type !== 'add' && !isEdit"
                hide-button
              >
                <!-- <template #append>
                  <a-select
                    placeholder="单位"
                    v-model="form.list.equipmentAge.equipmentAgeUnit"
                    :disabled="type !== 'add' && !isEdit"
                  >
                    <a-option>年</a-option>
                    <a-option>月</a-option>
                    <a-option>日</a-option>
                  </a-select>
                </template> -->
              </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="equipmentStandardLife"
              label="设备标准寿命："
              required
            >
              <a-input-group>
                <a-input-number
                  :min="1"
                  placeholder="请输入"
                  size="large"
                  v-model="form.list.equipmentStandardLife"
                  :disabled="type !== 'add' && !isEdit"
                  hide-button
                >
                  <!-- <template #append>
                  <a-select
                    placeholder="单位"
                    v-model="form.list.equipmentStandardLifeUnit"
                    :disabled="type !== 'add' && !isEdit"
                  >
                    <a-option :value="1">天</a-option>
                    <a-option :value="1">数量</a-option>
                  </a-select>
                </template> -->
                </a-input-number>
                <a-cascader
                  style="height: 36px"
                  :disabled="type !== 'add' && !isEdit"
                  v-model="form.list.equipmentStandardLifeUnit"
                  placeholder="单位"
                  :options="[
                    {
                      value: 1,
                      label: '时间',
                      children: [
                        { value: 3, label: '天' },
                        { value: 2, label: '月' },
                        { value: 1, label: '年' },
                      ],
                    },
                    {
                      value: 4,
                      label: '数量',
                      children: [
                        { value: 4, label: '件' },
                        { value: 5, label: '个' },
                        { value: 6, label: '条' },
                        { value: 7, label: '台' },
                      ],
                    },
                  ]"
                />
              </a-input-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              field="maintenanceCycleNum"
              label="设备保养周期："
              required
            >
              <a-input-group>
                <a-input-number
                  :min="1"
                  placeholder="请输入"
                  size="large"
                  v-model="form.list.maintenanceCycleNum"
                  :disabled="type !== 'add' && !isEdit"
                  hide-button
                >
                  <!-- <template #append>
                  <a-select
                    placeholder="单位"
                    v-model="form.list.maintenanceCycleUnit"
                    :disabled="type !== 'add' && !isEdit"
                  >
                    <a-option :key="1" :label="'天'" :value="1"></a-option>
                    <a-option :key="1" :label="'数量'" :value="2"></a-option>
                  </a-select>
                </template> -->
                </a-input-number>
                <a-cascader
                  style="height: 36px"
                  :disabled="type !== 'add' && !isEdit"
                  v-model="form.list.maintenanceCycleUnit"
                  placeholder="单位"
                  :options="[
                    {
                      value: 1,
                      label: '时间',
                      children: [
                        { value: 3, label: '天' },
                        { value: 2, label: '月' },
                        { value: 1, label: '年' },
                      ],
                    },
                    {
                      value: 4,
                      label: '数量',
                      children: [
                        { value: 4, label: '件' },
                        { value: 5, label: '个' },
                        { value: 6, label: '条' },
                        { value: 7, label: '台' },
                      ],
                    },
                  ]"
                />
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="maintenanceCycleAlarmRemainder"
              label="设备保养预警："
              validate-trigger="blur"
              required1
            >
              周期保养内剩余
              <a-input-number
                :min="1"
                size="large"
                style="width: 80px; margin: 0 8px"
                v-model="form.list.maintenanceCycleAlarmRemainder"
                :disabled="type !== 'add' && !isEdit"
                hide-button
              />
              {{
                [1, 2, 3].indexOf(form.list.maintenanceCycleUnit) === -1
                  ? '件'
                  : '天'
              }}，开始预警
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="计量单位：">
              <a-cascader
                :disabled="type !== 'add' && !isEdit"
                @change="changeUnit"
                v-model="form.list.measurementUnitId"
                :options="unitData.data"
                :style="{ width: '320px' }"
                placeholder="选择计量单位"
                :field-names="{ value: 'id', label: 'name', children: 'item' }"
                expand-child
              />
              <!-- <a-radio-group
                size="large"
                v-model="form.list.measurementUnit.unitType"
                :disabled="type !== 'add' && !isEdit"
              >
                <a-radio
                  :value="1"
                  :style="{
                    marginRight: '20px'
                  }"
                >
                  <template #radio="{ checked }">
                    <div
                      :style="{
                        display: 'flex',
                        width: '135px'
                      }"
                      :class="checked ? 'checked-radio' : 'unchecked-radio'"
                    >
                      <div
                        :style="{
                          width: '35px',
                          textAlign: 'center'
                        }"
                        :class="
                          checked
                            ? 'radio-icon-box-checked'
                            : 'radio-icon-box-unchecked'
                        "
                      >
                        <icon-check-circle
                          :class="
                            checked
                              ? 'radio-icon-checked'
                              : 'radio-icon-unchecked'
                          "
                          class="radio-icon"
                          size="20px"
                        />
                      </div>
                      <div
                        :style="{
                          width: '100px',
                          textAlign: 'center'
                        }"
                      >
                        单计量
                      </div>
                    </div>
                  </template>
                </a-radio>
                <a-radio :value="2">
                  <template #radio="{ checked }">
                    <div
                      :style="{
                        display: 'flex',
                        width: '135px'
                      }"
                      :class="checked ? 'checked-radio' : 'unchecked-radio'"
                    >
                      <div
                        :style="{
                          width: '35px',
                          textAlign: 'center'
                        }"
                        :class="
                          checked
                            ? 'radio-icon-box-checked'
                            : 'radio-icon-box-unchecked'
                        "
                      >
                        <icon-check-circle
                          :class="
                            checked
                              ? 'radio-icon-checked'
                              : 'radio-icon-unchecked'
                          "
                          class="radio-icon"
                          size="20px"
                        />
                      </div>
                      <div
                        :style="{
                          width: '100px',
                          textAlign: 'center'
                        }"
                      >
                        多计量
                      </div>
                    </div>
                  </template>
                </a-radio>
              </a-radio-group> -->
            </a-form-item>
          </a-col>

          <!-- <a-col :span="12">
            <div
              :style="{
                display: 'flex'
              }"
            >
              <div v-if="form.list.measurementUnit.unitType === 2">
                <a-select
                  placeholder="请选择"
                  :style="{
                    width: '200px'
                  }"
                  v-model="form.list.measurementUnit.unitGroup.mainUnit"
                  :disabled="type !== 'add' && !isEdit"
                >
                  <template #prefix>计量单位组</template>
                  <a-option>件</a-option>
                  <a-option>个</a-option>
                  <a-option>条</a-option>
                  <a-option>台</a-option>
                </a-select>
              </div>
              <div
                :style="{
                  marginLeft: '20px'
                }"
              >
                <a-select
                  placeholder="请选择"
                  v-model="form.list.measurementUnit.unitGroup.subUnit"
                  :style="{
                    width: '200px'
                  }"
                  :disabled="type !== 'add' && !isEdit"
                >
                  <template #prefix>计量单位</template>
                  <a-option>件</a-option>
                  <a-option>个</a-option>
                  <a-option>条</a-option>
                  <a-option>台</a-option>
                </a-select>
              </div>
            </div>
          </a-col> -->
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12" class="dept">
            <a-form-item label="单位产能：">
              <a-input-group>
                <a-input-number
                  :min="1"
                  style="flex: 1"
                  placeholder="请输入"
                  size="large"
                  :disabled="type !== 'add' && !isEdit"
                  v-model="form.list.unitCapacity"
                >
                </a-input-number>
                <!-- <a-select
                  style="height: 36px"
                  placeholder="请选择"
                  v-model="form.list.unitCapacitys.timeUnit"
                  :disabled="type !== 'add' && !isEdit"
                >
                  <a-option :value="1">小时</a-option>
                  <a-option :value="2">天</a-option>
                </a-select> -->
                <div
                  :disabled="type !== 'add' && !isEdit"
                  :class="{
                    isEdit: type !== 'add' && !isEdit,
                  }"
                  style="
                    /* border: 1px solid #c9cdd4; */
                    width: 100%;
                    height: 36px;
                    padding: 8px;
                    text-align: center;
                    background-color: #e5e6eb;
                  "
                >
                  {{ unitName ? unitName : '请选择计量单位' }} /天
                </div>
                <!-- <a-input-number :min="1"
                  placeholder="请输入"
                  size="large"
                  :disabled="type !== 'add' && !isEdit"
                  v-model="form.list.unitCapacitys.count"
                >
                </a-input-number>
                <div
                  :disabled="type !== 'add' && !isEdit"
                  :class="{
                    isEdit: type !== 'add' && !isEdit
                  }"
                  style="
                    border: 1px solid #c9cdd4;
                    width: 100%;
                    height: 36px;
                    padding: 8px;
                  "
                  >件</div
                > -->
              </a-input-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12" class="dept">
            <a-form-item label="产能负荷：">
              <a-input-number
                :min="1"
                placeholder="请输入"
                size="large"
                :style="{ width: '300px' }"
                style="padding: 0 30px"
                class="free"
                v-model="form.list.spareLoad"
                :disabled="type !== 'add' && !isEdit"
              >
                <template #prefix>
                  {{ `<=` }}
                </template>
                <template #prepend>
                  <div style="color: #f7f8fa">良好</div>
                </template>
                <template #append> % </template>
              </a-input-number>
              <a-input-number
                :min="1"
                placeholder="请输入"
                size="large"
                :style="{ width: '300px' }"
                style="padding: 0 30px"
                class="middle"
                v-model="form.list.middleLoad"
                :disabled="type !== 'add' && !isEdit"
              >
                <template #prefix>
                  {{ `>=` }}
                </template>
                <template #prepend>
                  <div style="color: #f7f8fa">中等</div>
                </template>
                <template #append> % </template>
              </a-input-number>
              <a-input-number
                :min="1"
                placeholder="请输入"
                size="large"
                :style="{ width: '300px' }"
                style="padding: 0 30px"
                class="top"
                v-model="form.list.peakLoad"
                :disabled="type !== 'add' && !isEdit"
              >
                <template #prefix>
                  {{ `>=` }}
                </template>
                <template #prepend>
                  <div style="color: #f7f8fa">峰值</div>
                </template>
                <template #append> % </template>
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              label="是否需要持证上岗："
              validate-trigger="blur"
              required
            >
              <a-radio-group
                size="large"
                v-model="form.list.isCertificate"
                :disabled="type !== 'add' && !isEdit"
              >
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
            </a-form-item>
            <!-- <a-form-item
              field="level"
              label="持证授权人员："
              v-if="form.list.isCertificate.state === 1"
            >
              <a-select
                placeholder="请选择"
                v-model="form.list.isCertificate.id"
                :disabled="type !== 'add' && !isEdit"
              >
                <a-option>件</a-option>
                <a-option>个</a-option>
                <a-option>条</a-option>
                <a-option>台</a-option>
              </a-select>
            </a-form-item> -->
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12" class="dept">
            <a-form-item label="备注：">
              <a-textarea
                placeholder="请输入"
                allow-clear
                :max-length="300"
                v-model="form.list.remark"
                show-word-limit
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="是否启用：">
              <a-switch
                v-model="form.list.isEnabled"
                :disabled="type !== 'add' && !isEdit"
              />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="设备完好状态：">
              <a-select
                placeholder="单位"
                v-model="form.list.goodState"
                :disabled="type !== 'add' && !isEdit"
              >
                <a-option
                  v-for="item in goodStateList.list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col> -->
        </a-row>
        <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
        <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
        <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
      </a-form>
      <a-row :gutter="16">
        <a-col :span="12">
          <span style="margin-top: 20px"
            >设备资料：支持PDF、Word、Excel、TXT文档格式，100M以内</span
          >
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <UploadFile
            style="margin-top: 20px"
            :disabled="type !== 'add' && !isEdit"
            :file-type-list="['pdf', 'docx', 'xlsx', 'txt']"
            :isShowRemove="type === 'add' || isEdit"
            ref="refUploadFile"
            v-model:fileList="equipmentData"
            :limit="0"
            :args="{
              onBeforeRemove: (e:any) => remove(e, 1),
              download:true
            }"
          />
          <!-- {{ equipmentData }} -->
          <!-- <div
            class="file"
            v-for="(item, index) in form.list.equipmentData"
            :key="item.uid"
          >
            <a-input style="width: 50%" v-model="item.name"></a-input>
            <div class="main">
              <div style="display: flex; align-items: center">
                <icon-book :size="20" />
                <p style="margin-left: 10px">{{
                  item.oldName ? item.oldName : item.name
                }}</p>
              </div>

              <div class="btn">
                <p @click="preview(item)">预览</p>
                <p @click="delFile(index)">删除</p>
              </div>
            </div>
          </div>
          <a-upload
            :disabled="type !== 'add' && !isEdit"
            @success="uploadFn($event, 'file')"
            :on-before-upload="(e) => beforeUpload(e, 'file')"
            style="margin: 20px 20px"
            name="data"
            :action="url"
            :headers="{ Authorization: `${getToken()}` }"
          >
            <template #upload-item> </template>
          </a-upload> -->
        </a-col>
      </a-row>
      <a-row style="margin-top: 20px" :gutter="16">
        <a-col :span="12">
          <span>设备照片：</span>
          <UploadFile
            :file-type-list="['JPEG', 'JPG', 'PNG', 'GIF', 'SVG']"
            style="margin-top: 20px"
            :disabled="type !== 'add' && !isEdit"
            :isShowRemove="type === 'add' || isEdit"
            ref="refUploadFile"
            v-model:fileList="equipmentPictures"
            listType="picture-card"
            :limit="0"
            :args="{
              onBeforeRemove: (e:any) => remove(e, 2),
              download:true
            }"
          />
        </a-col>
      </a-row>

      <div
        :style="{
          float: 'right',
        }"
      >
        <a-button type="primary" v-if="isEdit" @click="saveDetail">
          保存
        </a-button>
      </div>
    </div>
    <div class="box" v-if="type === 'add'">
      <a-space
        ><a-button type="primary" @click="save">保存</a-button>
        <a-button @click="cancel">取消</a-button></a-space
      >
    </div>
  </div>
  <personnelModel
    @personnelId="changePersonnelId"
    v-model:personnelVisible="personnelVisible"
  />
</template>

<script lang="ts" setup>
  import { getToken } from '@/utils/auth';
  import { reactive, ref, computed, watchEffect } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { GetUnitList } from '@/api/inventory-management/material-management/index';
  import { GetSupplierPrimaryList } from '@/api/buy-management/supplier-management/supplier-primary-list';
  import { GetWorkshopPage } from '@/api/FactoryModeling';
  import {
    PostEquipment,
    GetEquipmentDetail,
    PutEquipment,
    DelFile,
    DelPicture,
  } from '@/api/equipment-management/equipment-list';

  import { GetEquipmentType } from '@/api/equipment-management/base-setting';
  import {
    GetEquipmentGoodState,
    GetCapacityLoads,
  } from '@/api/equipment-management/base-setting';
  import { Message } from '@arco-design/web-vue';
  import { GetPersonnelinformation } from '@/api/home/System settings/personal-information/index';
  import personnelModel from './personnelModel/index.vue';

  const env = import.meta.env;
  const url = env.VITE_UPLOAD_URL;
  const capacityLoadData = reactive({ data: [] });

  // 设备保养预警单位
  const upkeepCycleUnit = ['年', '月', '天', '件', '个', '条', '台'];
  const formRef = ref();
  const router = useRouter();
  const route = useRoute();
  const title: string = '新增设备';
  const type = route.query.type; // 判断是新增还是详情
  const id = Number(route.query.id); // 设备id
  const personnelVisible = ref(false);
  const breadCrumb: string[] = ['设备管理', '设备列表', '新增设备'];

  const form = reactive<any>({
    list: {
      manufacturerNumber: '', // 设备厂商编号
      deviceName: '', // 设备名称
      supplierID: null, // 供应商Id
      specification: '', // 规格
      modelNumber: '', // 型号
      deviceTypeId: null, // 设备类型
      deviceUse: '', // 设备用途
      workshopId: null, // 车间
      storageLocation: '', // 存放位置
      responsiblePersonId: null, // 负责人id
      responsiblePersonName: '', // 负责人名字
      productionDate: 0, // 投产日期
      // goodState: 1, // 设备完好状态
      purchaseAmount: 0, // 设备购置金额数额
      purchaseAmountUnit: 1, // 设备购置金额单位
      // 设备购置金额
      installationCost: '', // 设备安装费用金额
      installationCostUnit: 1, // 设备安装费用单位
      brand: '', // 设备品牌
      periodOfDepreciation: null, // 设备折旧年限值
      equipmentAge: null, // 设备折旧年龄
      equipmentStandardLifeUnit: 1, // 设备标准寿命单位
      equipmentStandardLife: null, // 设备标准寿命值
      maintenanceCycleUnit: 1, // 设备保养周期单位
      maintenanceCycleNum: null, // 设备保养周期值
      maintenanceCycleAlarm: null, // 保养预警余量
      measurementUnitId: null, // 计量单位id
      unitCapacity: 0, // 单位产能
      spareLoad: null, // 产能负荷空闲值
      middleLoad: null, // 产能负荷中等负荷
      peakLoad: null, // 产能负荷峰值
      isCertificate: false, // 是否需要持证上岗
      isEnabled: true, // 是否启用
      remark: '', // 备注
      // 设备资料
      equipmentData: [],
      // 设备图片
      equipmentPictures: [],
    },
  });

  // const unit = computed(()=>{
  //   unitData.data.forEach((ele)=>{
  //     ele.item.
  //   })
  //   return ''
  // })
  const remove = async (e: any, type: 1 | 2) => {
    try {
      if (e.id) {
        if (type === 2) {
          await DelPicture({ pictureId: e.id });
        } else {
          await DelFile({ fileId: e.id });
        }
      }
      return true;
    } catch (error) {
      console.log(error);
      Message.error('删除失败');
      return false;
    }
  };

  let equipmentData = computed({
    get() {
      return form.list.equipmentData[0] && form.list.equipmentData[0].file
        ? form.list.equipmentData.map((element: any) => {
            return {
              ...element,
              fileUrl: element.files ? element.files : element.file,
              fileName: element.name,
              sourceAddr: element.sourceAddr,
            };
          })
        : [];
    },
    set(val: any[]) {
      form.list.equipmentData =
        val?.map((element) => {
          return {
            ...element,
            files: element.fileUrl,
            file: element.sourceAddr,
            name: element.fileName,
          };
        }) || [];
    },
  });

  let equipmentPictures = computed({
    get() {
      return form.list.equipmentPictures[0] &&
        form.list.equipmentPictures[0].picture
        ? form.list.equipmentPictures.map((element: any) => {
            return {
              ...element,
              fileUrl: element.picture ? element.picture : element.sourceAddr,
              fileName: element.name,
              sourceAddr: element.sourceAddr,
            };
          })
        : [];
    },
    set(val: any[]) {
      form.list.equipmentPictures = val.map((element) => {
        return {
          ...element,
          files: element.fileUrl,
          picture: element.sourceAddr,
          name: element.fileName,
        };
      });
    },
  });

  const workshop = reactive<{ data: { id: number; name: string }[] }>({
    data: [],
  });
  const unitData: any = reactive({ data: [] });
  const unitName = ref('');
  const deviceType: any = reactive({ data: [] });
  const rules = {
    manufacturerNumber: { required: true, message: '设备厂商编号不能为空' },
    deviceName: { required: true, message: '设备名称不能为空' },
    supplierID: { required: true, message: '供应商不能为空' },
    specification: { required: true, message: '规格不能为空' },
    deviceTypeId: { required: true, message: '设备类型不能为空' },
    deviceUse: { required: true, message: '设备用途不能为空' },
    workshopId: { required: true, message: '所属车间不能为空' },
    responsiblePersonId: { required: true, message: '负责人不能为空' },
    productionDate: { required: true, message: '投产日期不能为空' },
    purchaseAmount: { required: true, message: '设备购置金额不能为空' },
    periodOfDepreciation: { required: true, message: '设备折旧年限不能为空' },
    equipmentStandardLife: { required: true, message: '设备标准寿命不能为空' },
    maintenanceCycleNum: { required: true, message: '设备保养周期不能为空' },
    maintenanceCycleAlarm: { required: true, message: '设备保养预警不能为空' },
  };
  // 表单校验
  const validateField = async () => {
    const res = await formRef.value.validate();
    return res;
  };

  const inputMoney = reactive([
    { name: '人民币', symbol: '￥' },
    { name: '美元', symbol: '$' },
    { name: '英镑', symbol: '£' },
  ]);

  const emuipmentAge = [
    {
      value: 1,
      label: '时间',
      children: [
        { value: 3, label: '天' },
        { value: 2, label: '月' },
        { value: 1, label: '年' },
      ],
    },
    {
      value: 4,
      label: '数量',
      children: [
        { value: 4, label: '件' },
        { value: 5, label: '个' },
        { value: 6, label: '条' },
        { value: 7, label: '台' },
      ],
    },
  ];

  const getDetailData = async () => {
    try {
      const res = await GetEquipmentDetail({
        id,
        typeId: 0,
      });
      const res1 = await GetPersonnelinformation({
        page: 1,
        size: -1,
      });
      form.list = res;
      form.list.supplierId = form.list.supplierID;
      form.list.equipmentPictures.forEach((ele: any, index: number) => {
        ele.uid = ele.id;
        ele.name = `${index}`;
        ele.url = ele.picture;
      });
      form.list.purchaseAmount = Number(form.list.purchaseAmount);
      form.list.installationCost = Number(form.list.installationCost);
      form.list.responsiblePersonName = res1.content.data?.filter(
        (ele: any) => ele.id === form.list.responsiblePersonId
      )[0]?.name;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  const changePersonnelId = (e: { id: number; name: string }) => {
    form.list.responsiblePersonId = e.id;
    form.list.responsiblePersonName = e.name;
  };
  let isExistDeviceCoding = 0; // 判断设备编码是否存在，校验时候用到

  // 供应商下拉框数据
  const supplierList = reactive<any>({
    list: [],
  });

  // 设备完好状态下拉框数据
  const goodStateList = reactive<any>({
    list: [],
  });

  // 获取全部供应商列表，设备完好状态数据
  const getBasicData = async () => {
    try {
      let res3 = await GetWorkshopPage({
        page: 1,
        size: -1,
      });
      workshop.data = res3.content;
      const res1 = await GetEquipmentType();
      const res2 = await GetUnitList({ page: 1, size: -1, type: 1 });
      if (type === 'add') {
        const res4 = await GetCapacityLoads();
        // spareLoad: null, // 产能负荷空闲值
        // middleLoad: null, // 产能负荷中等负荷
        // peakLoad: null, // 产能负荷峰值
        form.list.spareLoad = res4[0].value;
        form.list.middleLoad = res4[1].value;
        form.list.peakLoad = res4[2].value;
        capacityLoadData.data = res4;
      }

      const res = await Promise.all([
        GetSupplierPrimaryList({ page: 1, size: -1 }),
        GetEquipmentGoodState({
          type: 3,
        }),
      ]);
      supplierList.list = res[0].content;

      if (form.list?.supplierName) {
        for (let i of supplierList.list) {
          if (i.name === form.list.supplierName) form.list.supplierID = i.id;
        }
      }
      supplierList.list = supplierList.list.filter(
        (ele: any) => ele.enabled === 1
      );
      deviceType.data = res1;
      goodStateList.list = res[1];
      unitData.data = res2.content;
    } catch (error: unknown) {
      console.log(error);
    }
  };

  watchEffect(async () => {
    // 如果是详情编辑页面就获取详情对应数据
    if (type !== 'add') {
      await getDetailData();
      await getBasicData();
    } else {
      await getBasicData();
    }
  });
  const changeUnit = (e: any) => {
    const list: any = [];
    unitData.data?.forEach((ele: any) => {
      ele.item.forEach((item: any) => {
        list.push(item);
      });
    });
    unitName.value = list.filter((ele: any) => ele.id === e)[0].name;
  };
  let isEdit = ref(false); // 判断用户是否点击编辑按钮
  const edit = () => {
    isEdit.value = !isEdit.value;
  };

  // 获取供应商id
  const selectSupplier = (id: number) => {
    form.list.supplierID = id;
  };

  // 获取负责人id
  const selectResponsible = () => {
    form.list.responsiblePersonId = 1;
  };

  let file = ref(); // 储存图片
  let headPortraitFormData = new FormData();
  // 上传头像事件
  const onChange = (fileList: any, currentFile: any) => {
    file.value = {
      ...currentFile,
      url: URL.createObjectURL(currentFile.file),
    };
    headPortraitFormData.append('headPortrait', currentFile.file);
  };

  const onProgress = (currentFile: any) => {
    file.value = currentFile;
  };

  // 保存新增时候的数据
  const save = async () => {
    try {
      const aaaa = await formRef.value.validate();

      if (aaaa) {
        return;
      }
      form.list.productionDate = Number(form.list.productionDate);
      form.list.purchaseAmount = String(form.list.purchaseAmount);
      form.list.installationCost = String(form.list.installationCost);

      // form.list.installationCost = String(form.list.purchaseAmount);
      // form.list.purchaseAmount = String(form.list.purchaseAmount);
      // form.list.purchaseAmount = String(form.list.purchaseAmount);
      await PostEquipment(form.list);
      router.back();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 保存详情编辑后的数据
  const saveDetail = async () => {
    try {
      delete form.list.supplierName;
      delete form.list.responsiblePersonName;
      form.list.productionDate = Number(form.list.productionDate);
      form.list.purchaseAmount = String(form.list.purchaseAmount);
      form.list.installationCost = String(form.list.installationCost);
      form.list.equipmentPictures = form.list.equipmentPictures.filter(
        (ele: any) => !ele.id
      );
      await PutEquipment(form.list);
      router.back();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  const regularFileFn = (name: string, type: string) => {
    const regex =
      type === 'file'
        ? /^(.+)\.(pdf|docx|xlsx|txt)$/i
        : /^(.+)\.(JPEG|JPG|PNG|GIF|SVG)$/i;
    const match = name.match(regex);
    if (match) {
      return match[1];
    } else {
      throw new Error('上传文件有问题');
    }
  };
  // 上传文件
  // const uploadFn = (flie: any, type: string) => {
  //   try {
  //     if (type === 'file') {
  //       form.list.equipmentData.push({
  //         name: regularFileFn(flie.name, type),
  //         oldName: flie.name,
  //         file: flie.response.data.sourceAddr,
  //         uid: flie.uid,
  //       });
  //     } else {
  //       form.list.equipmentPictures.push({
  //         name: regularFileFn(flie.name, type),
  //         url: flie.response.data.addr,
  //         picture: flie.response.data.sourceAddr,
  //         uid: flie.uid,
  //       });
  //     }
  //   } catch (error: any) {
  //     Message.error(error.message);
  //     console.log(error);
  //   }
  // };
  // 上传前校验
  const beforeUpload = (file: any, type: string) => {
    try {
      regularFileFn(file.name, type);
      return true;
    } catch (error: any) {
      Message.error(error.message);
      console.log(error);
      return false;
    }
  };

  const preview = (ele: any) => {
    const link = document.createElement('a');
    link.href = ele.file;
    link.download = ele.name;
    // link.target = '_blank'; // 可选，设置为"_blank"以在新窗口中打开链接
    link.click();
  };
  // 取消按钮
  const cancel = () => router.back();
</script>

<style scoped lang="less">
  .base-info {
    padding: 20px;
    .dept {
      :deep(.arco-form-item-content-wrapper) {
        width: 200%;
      }
    }
    :deep(.arco-input-wrapper .arco-input[disabled]),
    :deep(.arco-select-view-single .arco-select-view-input[disabled]),
    :deep(.arco-select-view-single.arco-select-view-disabled),
    :deep(.arco-picker-disabled input[disabled], .arco-picker-disabled:hover
        input[disabled]),
    :deep(.arco-textarea[disabled]),
    :deep(.arco-radio-checked.arco-radio-disabled .arco-radio-label) {
      -webkit-text-fill-color: #165dff;
    }
    .free {
      :deep(.arco-input-prepend) {
        background-color: #00b42a;
      }
    }

    .middle {
      :deep(.arco-input-prepend) {
        background-color: #ff9a2e;
      }
    }

    .top {
      :deep(.arco-input-prepend) {
        background-color: #f53f3f;
      }
    }

    .unchecked-radio {
      background-color: #fff;
      color: #dcdfe6;
      border: 1px solid #dcdfe6;
      font-weight: 700;
      font-size: 16px;
    }
    .checked-radio {
      background-color: #3491fa;
      color: #fff;
      border: 1px solid #3491fa;
      font-weight: 700;
      font-size: 16px;
    }
    .radio-icon-box-checked {
      border: 1px solid #3491fa;
      background-color: #fff;
    }
    .radio-icon-box-unchecked {
      border: 1px solid rgba(220, 223, 230, 1);
    }
    .radio-icon-checked {
      color: #3491fa;
    }

    .radio-icon {
      position: absolute;
      position: relative;
      top: 3px;
    }
  }
  .success {
    position: absolute;
    right: 30px;
    background-color: #31c27c;
    color: #fff;
    border-radius: 100%;
    width: 50px;
    text-align: center;
  }
  .blacklist {
    position: absolute;
    right: 30px;
    background-color: red;
    color: #fff;
    margin-left: 20px;
    border-radius: 100%;
    width: 50px;
    text-align: center;
  }
  :deep(.arco-input-wrapper) {
    box-sizing: border-box;
  }
  .file {
    width: 50%;
    margin: 10px 0;
    .main {
      display: flex;
      border: 1px solid #409eff;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      margin-top: 10px;
      .btn {
        display: flex;
        p {
          cursor: pointer;
          margin-left: 10px;
        }
        P:nth-child(1) {
          color: #48c98a;
        }
        P:nth-child(2) {
          color: #ff5a5a;
        }
      }
    }
  }
  .isEdit {
    background-color: #f2f3f5;
    cursor: not-allowed;
    border: none !important;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }
</style>
